<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../../res/layui/css/layui.css" media="all">
    <script src="../../../res/js/jquery-3.4.1.min.js"></script>
    <link rel="stylesheet" href="../../lib/layui/lay/mymodules/eleTree.css">
    <style>
        .divbu {

            white-space: nowrap;
            float: left;
            overflow-y: auto;
        }
    </style>
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body>


<div id="pdetail" style="height:550px;">

    <div style="width: 20%;height: 500px;" class="divbu">
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
            <legend>点击节点查询</legend>
        </fieldset>
        <div id="test2" class="eleTree ele5" lay-filter="data5"></div>
    </div>
    <div style="width: 80%" class="divbu">
        <table class="layui-hide" class="list" id="test" lay-filter="test"></table>
    </div>
    <div style="width: 100%" class="divbu">
        <table class="layui-hide" id="test1" lay-filter="test1"></table>`
    </div>
</div>

<div id="plan"  style="height: 100%;">
    <fieldset class="layui-elem-field layui-field-title" style="margin-left: 20%;width:60%;">
        <legend>生产计划维护</legend>
    </fieldset>

    <form class="layui-form" action="" lay-filter="forms" style="width:60%;margin-left: 20%;">
        <div class="layui-form-item">
            <label class="layui-form-label">计划名称</label>
            <div class="layui-input-block">
                <input type="text"  name="planName" maxlength="30" autocomplete="off"  lay-verify="required" lay-reqtext="不能为空" placeholder="请输入名称"
                       class="layui-input" >
                <input type="hidden" id="planId" name="planId">
            </div>
        </div>


        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">开始时间</label>
                <div class="layui-input-inline">
                    <input type="text" class="layui-input"  readonly  lay-verify="required" lay-reqtext="不能为空" autocomplete="off" name="planKtime" id="test5" placeholder="yyyy-MM-dd">
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">结束时间</label>
                <div class="layui-input-inline">
                    <input type="text" class="layui-input" readonly lay-verify="required" lay-reqtext="不能为空" autocomplete="off" name="planJtime" id="test6" placeholder="yyyy-MM-dd">
                </div>
            </div>
        </div>


        <div class="layui-form-item">
            <div class="layui-form-item">
                <label class="layui-form-label">操作人</label>
                <div class="layui-input-block">
                    <input type="text" id="oper" name="oper"    placeholder="请输入操作人" autocomplete="off"
                           class="layui-input layui-disabled" disabled="">
                </div>
            </div>
        </div>

        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">计划说明</label>
            <div class="layui-input-block">
                <textarea placeholder="请输入内容" maxlength="2000" name="remark" class="layui-textarea"></textarea>
            </div>
        </div>

        <div class="layui-form-item" hidden>
            <div class="layui-input-block">
                <button type="submit" id="dd" class="layui-btn" lay-submit="" lay-filter="demo1">立即提交</button>
            </div>
        </div>
    </form>
</div>




<div style="text-align: center;width: 100%;height: 1px;">
    <button type="submit" id="pdetailBtn" class="layui-btn" >下一步</button>
    <button type="submit" id="planBtn" class="layui-btn">上一步</button>
    <button class="layui-btn" id="baocun" lay-event="getData">一键保存</button>
</div>

<script src="../../../res/layui/layui.js" charset="utf-8"></script>
<script type="text/html" id="toolbarDemo">
    <div class="layui-inline">
        <label class="layui-form-label">药品名称</label>
        <div class="layui-input-inline">
            <input type="text" maxlength="50" id="drugName" placeholder="请输入药品名称" class="layui-input">
        </div>
    </div>

    <div class="layui-btn-container layui-inline">

        <button class="layui-btn" lay-event="reload">搜索</button>
        <button class="layui-btn" id="all" lay-event="getAll">全部药品</button>
    </div>
    <!--<button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>-->

</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs" lay-event="addDrug">药品操作</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script type="text/html" id="barDemo1">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script type="text/html" id="img">
    <img src="{{d.images}}" width="50" height="50" onclick="showBig(this)"/>
</script>

<script type="text/html" id="remark">
    <input type="text" id="{{d.drugId}}" value="{{d.remark}}" autocomplete="off" onblur="getRemark(this)" style=" width:100%;height:100%;border: none;" maxlength="100">
</script>

<!-- 注意：如果你直接复制所有代码到本地，上述js路径需要改成你本地的 -->
<script>
    let openIndex = null;
    var form = null;
    var layer = null;
    var layedit = null;
    var laydate = null;
    var util = null;
    var transfer = null;
    var formData = [];

    var el = null;
    var table = null;
    var array = new Array();
    var test1Data = [];
    var eleTree = null;
    var s= 0;

    layui.config({
        base: "../../lib/layui/lay/mymodules/"
    })
    window.init = function(){}
    layui.use(['form', 'layedit', 'laydate', 'transfer', 'layer', 'util','table','eleTree'], function () {

        table = layui.table;
        eleTree = layui.eleTree;
        form = layui.form
            , layer = layui.layer
            , layedit = layui.layedit
            , laydate = layui.laydate
            , util = layui.util
            , transfer = layui.transfer;

        getUserData();
        getData();
        el =  eleTree.render({
            elem: '#test2',
            method:'post',
            url: "../../../hqPdetail/getTypeTree",
            expandOnClickNode: false,
            highlightCurrent: true,
            defaultExpandAll: true,
            showLine:true
        });

        table.render({
            elem: '#test'
            , url: '../../../hqDrug/selectAll'
            , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            /*, defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                title: '提示'
                , layEvent: 'LAYTABLE_TIPS'
                , icon: 'layui-icon-tips'
            }]*/
            , title: '药品信息'
            , cols: [[
                {type: 'checkbox',LAY_CHECKED:false,fixed: 'left'}
                , {field: 'typeName', title: '类型', width: 120}
                , {field: 'drugName', title: '药品名称', width: 120}
                , {field: 'images', title: '药品图片', width: 100, templet:'#img'}
                , {field: 'alias', title: '别名', width: 100}
                , {field: 'drugRetail', title: '零售价', width: 150}
                , {field: 'drugWho', title: '批发价', width: 150}
                , {field: 'drugOut', title: '分店价', width: 100}
                , {field: 'drugExp', title: '药品说明', width: 150}
                , { field: 'taboo', title: '主要用药禁忌', width: 100}

                // , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 220}
            ]]
            , page: true
            , parseData: function (res) {//res 即为原始返回的数据
                ids = res.data;
                for(var i in res.data){
                    for(var j=0;j<array.length;j++){
                        if(array[j].drugId==res.data[i].drugId){

                            //如果set集合中有的话，给rows添加check属性选中
                            res.data[i]["LAY_CHECKED"] = true;
                        }
                    }


                }


                return {
                    "code": res.code, //解析接口状态
                    "count": res.count, //解析数据长度
                    "data": res.data //解析数据列表
                };
            }

        });

        form.on('submit(demo1)', function (data) {
            formData=data.field;
            console.info(formData);

                    $("#plan").hide();
                    $("#pdetail").show();
                    $("#pdetailBtn").hide();
                    $("#planBtn").show();
                    $("#baocun").show();

            return false;

        })

        // 节点点击事件
        eleTree.on("nodeClick(data5)",function(d) {
            table.reload('test',{
                where:{
                    typeId:d.data.currentData.id
                },
                page: {
                    curr: 1
                }
            })
        })



        table.on('checkbox(test)', function(obj){
            var checkStatus = table.checkStatus('test');
            var data = checkStatus.data;

            if(obj.type=="all"){

                if(data.length==0){
                    console.info(ids);
                    for(var i = 0;i<ids.length;i++){j
                        for(var j=0;j<array.length;j++){
                            if(ids[i].drugId==array[j].drugId ){
                                array.splice(j,1)
                            }
                        }

                    }
                }else{
                    $.each(data,function (index,item) {
                        if(JSON.stringify(array).indexOf(JSON.stringify(item.drugId))<0){
                            item.num=1;
                            item.remark = "";
                            item.planid = $("#planId").val();
                            array.push(item)
                        }

                    })

                }
            }else{
                if(!obj.checked){
                    for(var i=0;i<array.length;i++){
                        if(JSON.stringify(obj.data.drugId)==JSON.stringify(array[i].drugId)){
                            array.splice(i,1);
                            break;
                        }
                    }

                }else{
                    $.each(data,function (index,item) {
                        if(JSON.stringify(array).indexOf(JSON.stringify(item.drugId))<0){
                            item.planid = $("#planId").val();
                            item.num=1;
                            item.remark = "";
                            array.push(item)
                        }

                    })
                }
            }




            refresh(array);
        });




        table.on('edit(test1)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"


            var dd = obj.value.replace(/[^\d]/g,"");  //清除“数字”和“.”以外的字符
            if(dd == ""){
                dd =1;
            }else if(dd.indexOf("0")==0){
                dd = dd.substring(1,dd.length);
            }
            if(dd.length>6){
                dd = 1;
            }

            $(this).val(dd);

            for(var i=0;i<array.length;i++){
                if(array[i].drugId==obj.data.drugId){
                    array[i].num = dd
                }
            }

            /*refresh(array);*/

        });



        //头工具栏事件
        table.on('toolbar(test)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'getCheckLength':
                    var data = checkStatus.data;
                    layer.msg('选中了：' + data.length + ' 个');
                    break;
                case 'getAll':
                    table.reload('test',{
                        where:{
                            typeId:null,
                            drugName:null
                        }
                    });
                    break;
                case 'reload' :
                    table.reload('test',{
                        where:{
                            drugName:$("#drugName").val()
                        }
                    })
                    break;

                case 'detc':
                    layer.confirm('真的删除行么', function (index) {
                        var data = checkStatus.data;
                        var array = new Array();

                        console.info(data);
                        var dd = "";
                        $.each(data, function (index, item) {
                            array.push(item.userId)
                        });
                        array.join(",");
                        var url = "../deleteAll.action";
                        var dadd = {id: array.toString()};
                        $.post(url, dadd, function (obj) {
                            layer.msg(obj.msg);
                            if (obj.state == 1) {
                                layer.msg("删除成功");
                                table.reload("test");
                            }
                        }, "json")

                        layer.close(index);
                    });


                    break;

                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
                case 'query':
                    table.reload('test', {
                        where: {
                            userName: $("#name").val()
                        },

                        page: {
                            curr: 1
                        }
                    })
                    break;
            };
        });

        //监听行工具事件
        table.on('tool(test1)', function (obj) {
            var data = obj.data;
            if(obj.event==='del'){
                layer.confirm('真的删除行么', function (index) {
                    for(var i =0 ;i<array.length;i++){
                        if(array[i].drugId==data.drugId){
                            array.splice(i,1);
                            refresh(array);
                            table.reload("test")
                            break;
                        }

                    }

                    layer.close(index);
                });
            }
        })




        //日期
        //日期时间选择器
      var startDate =   laydate.render({
            elem: '#test5'
            ,type: 'datetime'
            ,min: 1
            ,trigger: 'click'
            ,done: function(value,date){
              endDate.config.min={
                  year:date.year,
                  month:date.month-1,//关键
                  date: date.date+1

              }
              var startTime  = value.replace("-","/");//替换字符，变成标准格式
              var endTime = $("#test6").val().replace("-","/")
              var d1 = new Date(Date.parse(startTime));
              var d2 = new Date(Date.parse(endTime));


              if(d1>=d2){
                  layer.msg("开始时间不能大于结束时间");
                  $("#test5").val("");
              }
          }
        });


       var endDate = laydate.render({
            elem: '#test6'
            ,type: 'datetime'
            ,min: 1
            ,trigger: 'click'
            ,max:"2099-12-31"//设置一个默认最大值
            ,btns: ['clear', 'confirm']
            ,done: function(value, date){
               startDate.config.max ={
                   year:date.year,
                   month:date.month-1, //关键
                   date: date.date-1
               };

           }
        });




        //创建一个编辑器

        //自定义验证规则
        form.verify({
            title: function (value) {
                if (value.length < 5) {
                    return '用户至少得5个字符啊';
                }
            }
            , pass: [
                /^[\S]{6,12}$/
                , '密码必须6到12位，且不能出现空格'
            ]
            , content: function (value) {
                layedit.sync(editIndex);
            }
        });
    });

    $("#planBtn").on('click',function(){

        $("#pdetail").hide();
        $("#plan").show();
        $("#pdetailBtn").show();
        $("#planBtn").hide();
        $("#baocun").hide();
    })

    //监听提交
    $("#pdetailBtn").on('click', function (){
        $("#dd").click();

    })


    $("#baocun").on('click',function () {
        s+=1;
        if(s==1){
            var url = "../../../hqPlan/insertPlanDetails";
            let loa ;
            if(array.length>0){
                $.ajax({
                    url:url,
                    data:{ wl: JSON.stringify(array),planJson:JSON.stringify(formData)},
                    type:"post",
                    dataType:"json",
                    traditional:true,
                    beforeSend:function(){
                        loa = layer.load(0,{shade:false,time: 4*1000});
                    },
                    success:function (obj) {
                        layer.close(loa);
                        if (obj.status == 20) {
                            layer.msg(obj.message)
                            //关闭当前弹出层
                            parent.closeOpen(obj.message);
                        }else{
                            s=0;
                            if(obj.data==null){
                                layer.msg(obj.message, {icon: 5, time: 2000});
                            }else{
                                layer.msg(obj.message+JSON.stringify(obj.data), {icon: 5, time: 2000});
                            }

                        }
                    }

                })
            }else{
                layer.msg("请选择计划生产的药品", {icon: 5, time: 2000})
                s=0;
            }
        }
    })


    /**
     * 关闭层
     */
    function closeOpen(msg) {
        layer.close(openIndex);
        layer.msg(msg, {time: 1000}, function () {
            table.reload("test");//刷新表格
        })
    }

    /**
     * 获取已有的生成计划详情
     */
    function getData(){
        $.ajax({
            url:"../../../hqPdetail/selectOne",
            type:"get",
            data:{planId:$("#planId").val()},
            dataType: "json",
            async:false,
            success:function (obj) {
                $.each(obj,function (index,item) {
                    array.push(item);
                })
                refresh(array);
            }
        })

    }

    function getRemark(obj){
        var drugId = $(obj).attr('id');
        for(let i in array){
            if(drugId==array[i].drugId){
                array[i].remark=$(obj).val()
            }
        }

        console.info(array)
    }


    /**
     * 图片
     */
    function showBig(obj) {
        $("#imgDiv").fadeToggle(1000);
        $("#imgDiv_img").prop("src", obj.src)
    }



    function refresh(obj){
        table.render({
            elem: '#test1'
            , data: obj
            , defaultToolbar:false
            , title: '生产计划'
            //,limit:obj.length
            //, toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            , cols: [[
                {field: 'typeName', title: '类型', width: '20%'}
                , {field: 'drugName', title: '药品名称', width: '20%'}
                , {field: 'num', title: '数量', width: '20%',edit:'test'}
                , {field: 'remark', title: '备注', width: '20%',templet:'#remark'}
                , {fixed: 'right', title: '操作', toolbar: '#barDemo1', width: '20%'}
            ]]
            ,done: function(res){
                test1Data = res.data;
            }
            , page: true
            ,text: {none: '请从上表选择药品'}
        });
    }

    function getUserData(){

            let users = window.localStorage.getItem("users");
            let data = JSON.parse(users);
            // console.info(data)
            $("#oper").val(data.userName);
    }
    $(function () {
        $("#pdetail").hide();
        $("#planBtn").hide();
        $("#baocun").hide();
    })
</script>

</body>
</html>